package com.zcsy.seller.web.report;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.ShopInfo;
import com.zcsy.manage.model.mall.GoodsInfo;
import com.zcsy.manage.service.mall.IGoodsInfoService;

/**
 * @Title: ReportController.java
 * @Package： com.zcsy.seller.web.coupon 
 * @Description: 报表控制层
 *
 * @author lilan 1063972142@qq.com
 * @Copyright: 2015 武汉恒数利通信息技术有限公司 All rights reserved.
 * @date 2016年8月17日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "salesVolumeReport")
public class SalesVolumeStatisticsController {
	
	@Autowired
	private IGoodsInfoService goodsInfoService;
	
	/**
	 * 
	 * @Description 返回销量额统计报表页面<br>
	 * 
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年8月17日
	 * @see
	 */
	@RequestMapping(value ="salesVolumeStatistics", method = RequestMethod.GET)
	public String salesVolumeStatistics(Model model) {
		
		return "report/salesVolumeStatistics";
	}
	
	/**
	 * 
	 * @Description 根据时间查询正常商品销售额，并生成折线图<br>
	 * 
	 * @param days 查询时间间隔天数
	 * @param type 查询类型，1：固定搜索-一周、月度、季度、年度，2：自由搜索-自定义时间
	 * @param beginDate 开始时间
	 * @param endDate 结束时间
	 * @param req 用户请求
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年8月26日
	 * @see
	 */
	@RequestMapping(value="salesVolumeEchartsShow" , method = RequestMethod.POST)
	@ResponseBody
    public RequestJson orderEchartsShow(Integer days,Integer type,String beginDate,String endDate, HttpServletRequest req){
		RequestJson result = new RequestJson();
		ShopInfo shopInfo = (ShopInfo)req.getSession().getAttribute(RequestConstants.SHOP_ID);
		try {
			List<GoodsInfo> goodsInfos = new ArrayList<GoodsInfo>();
			Map<String,BigDecimal> map = new HashMap<>();
			SimpleDateFormat sdf = DateUtils.yymd;
			List<Object> list = new ArrayList<Object>();
			String[] xAix = new String[days];
			String shopId = shopInfo.getId();

			if(Constants.SEARCH_FIXED == type){
				goodsInfos = goodsInfoService.getGoodsSales(shopId);
				Date currentTime =DateUtils.str2Date(DateUtils.getCurrentTime(), sdf); // yyyy/MM/dd
				Calendar rightNow = DateUtils.getCalendar();
				rightNow.setTime(currentTime);
				xAix = getXAxis(currentTime,rightNow,sdf ,Calendar.DAY_OF_YEAR,xAix,days);

			}else if(Constants.SEARCH_FREE == type){
				if(days <= 90 && days > 0){
					goodsInfos = goodsInfoService.searchGoodsSalesByTime(beginDate, endDate,shopId);
					Date endTime =DateUtils.str2Date(endDate, sdf); // yyyy/MM/dd
					Calendar end = DateUtils.getCalendar();
					xAix = getXAxis(endTime,end,sdf ,Calendar.DAY_OF_YEAR,xAix,days);
				}
			}

			for(GoodsInfo info:goodsInfos){
				String formatTime = sdf.format(DateUtils.date_sdf.parse(info.getSendTime().substring(0, 19)));
				if(map.containsKey(formatTime)){
					int sales = info.getSales();
					BigDecimal price = info.getPrice();
					map.put(formatTime,map.get(formatTime).add(info.getTotalMoney()));
				} else{
					map.put(formatTime,info.getTotalMoney());
				}
			}

			BigDecimal[] yAix = getYAxis(map,xAix,days);

			Map m = new HashMap();
			m.put(xAix, yAix);


			list.add(m.keySet());
			list.add(m.values());

			result.setObj(list);
			result.setSuccess(true);

		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
		}
		return result;
    }
	
	/**
	 * 
	 * @Description 获取x坐标轴数据<br>
	 * 
	 * @param time 传入时间
	 * @param calendar 转换时间
	 * @param sdf 转换时间格式
	 * @param xAix x坐标对象
	 * @param days 开始时间和结束时间之差
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年8月26日
	 * @see
	 */
	private String[] getXAxis(Date time,Calendar calendar,SimpleDateFormat sdf ,Integer calenderType,String[] xAix,Integer days){
		calendar.setTime(time);
		calendar.add(calenderType, 1);
		for(int i = days-1; i >= 0; i--){
			calendar.add(calenderType, -1);
			Date dt1=calendar.getTime();
			String reStr = sdf.format(dt1);
			xAix[i] = reStr;
         }
		return xAix;
	}
	
	/**
	 * 
	 * @Description 获取y坐标数据<br>
	 * 
	 * @param map 存放销量的map
	 * @param xAix x坐标
	 * @param days 开始时间与结束时间之差
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年8月26日
	 * @see
	 */
	private BigDecimal[] getYAxis(Map<String,BigDecimal> map,String[] xAix,Integer days){
		BigDecimal[] yAix = new BigDecimal[days];
        for(int i = 0; i < xAix.length; i ++){
      	  if(map.get(xAix[i]) == null){
      		  yAix[i] =new BigDecimal(0);
      	  } else {
      		  yAix[i] = map.get(xAix[i]);
      	  }
        }
		return yAix;
	}
	
	@RequestMapping(value="salesVolumeMonthEchartsShow" , method = RequestMethod.POST)
	@ResponseBody
	public RequestJson salesVolumeMonthEchartsShow(Integer seType,Integer monthSum,String beginDate,String endDate,HttpServletRequest req){
		RequestJson result = new RequestJson();
		ShopInfo shopInfo = (ShopInfo)req.getSession().getAttribute(RequestConstants.SHOP_ID);
		try {
			List<GoodsInfo> goodsInfos = new ArrayList<GoodsInfo>();
			List<Object> list = new ArrayList<Object>();
			Map<String, BigDecimal> map = new HashMap<>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
			String[] xAix = new String[monthSum];
			String shopId = shopInfo.getId();

			goodsInfos = goodsInfoService.searchSalesVolumeByMonth(seType,beginDate,endDate,shopId);
			if(Constants.SEARCH_FIXED == seType){
				Date currentTime =DateUtils.str2Date(DateUtils.getCurrentTime(), sdf); // yyyy/MM
				Calendar rightNow = DateUtils.getCalendar();
				xAix = getXAxis(currentTime,rightNow,sdf ,Calendar.MONTH,xAix,monthSum);

			} else if(Constants.SEARCH_FREE == seType){

				Date endTime =DateUtils.str2Date(endDate, sdf); // yyyy/MM/dd
				Calendar end = DateUtils.getCalendar();
				xAix = getXAxis(endTime,end,sdf ,Calendar.MONTH,xAix,monthSum);

			}

			for(GoodsInfo goodsInfo:goodsInfos){
				String formatTime = sdf.format(DateUtils.stringToDate(goodsInfo.getMonths(), "yyyyMM")); // yyyy/MM
				map.put(formatTime, goodsInfo.getTotalMoney());

			}

			BigDecimal[] yAix = getYAxis(map,xAix,monthSum);

			Map m = new HashMap();
			m.put(xAix, yAix);

			list.add(m.keySet());
			list.add(m.values());

			result.setObj(list);
			result.setSuccess(true);

		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
		}
		return result;
	}
}
